package tongcheng.com.tongcheng.base.main.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.yanzhenjie.nohttp.RequestMethod;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.Bind;
import tongcheng.com.tongcheng.ConStans;
import tongcheng.com.tongcheng.R;
import tongcheng.com.tongcheng.base.BaseActivity;
import tongcheng.com.tongcheng.network.CallServer;
import tongcheng.com.tongcheng.network.MyRequest;
import tongcheng.com.tongcheng.network.OnCallBack;
import tongcheng.com.tongcheng.utils.Setting;
import tongcheng.com.tongcheng.utils.ShowToast;
import tongcheng.com.tongcheng.zhifubao.PayResult;

public class ChongZhiActivity extends BaseActivity {

    @Bind(R.id.back)
    ImageView mBack;
    @Bind(R.id.title)
    TextView mTitle;
    @Bind(R.id.title_bar)
    RelativeLayout mBg;
    @Bind(R.id.chongzhi_ll1)
    LinearLayout mChongzhiLl1;
    @Bind(R.id.chongzhi_ok)
    Button mChongzhiOk;
    @Bind(R.id.rb_weiXinChongZhi)
    RadioButton rb_weiXinChongZhi;
    @Bind(R.id.rb_zhiFuBaoChongZhi)
    RadioButton rb_zhiFuBaoChongZhi;
    @Bind(R.id.et_chongZhiJinE)
    EditText et_chongZhiJinE;
    public int temp = 0;

    @Override
    public Integer initResid() {
        return R.layout.activity_chong_zhi;
    }

    @Override
    public void initCreate(Bundle savedInstanceState) {
        settitlebar(mBg);
        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mTitle.setText("充值中心");

        //微信支付
        rb_weiXinChongZhi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    temp = 1;
                    rb_zhiFuBaoChongZhi.setChecked(false);
                }
            }
        });

        //支付宝支付
        rb_zhiFuBaoChongZhi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    temp = 2;
                    rb_weiXinChongZhi.setChecked(false);
                }
            }
        });

        //确认充值
        mChongzhiOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String jine = et_chongZhiJinE.getText().toString().trim();

                if (temp == 1) {//微信
                    if(TextUtils.isEmpty(jine)){
                        ShowToast.showToast("请输入充值金额");
                    }else {
                        double num = Double.parseDouble(jine);
                        if(num >= 100){
                            ShowToast.showToast("你选择了微信支付");
                            boolean isWeiXin = isWeixinAvilible(ChongZhiActivity.this);
                            if(isWeiXin){
                                //微信支付
//                                WeiXInPay(jine);
                            }else {
                                ShowToast.showToast("你尚未安装微信");
                            }

                        }else {
                            ShowToast.showToast("最低充值100元");
                        }
                    }

                } else if (temp == 2) {//支付宝
                    if(TextUtils.isEmpty(jine)){
                        ShowToast.showToast("请输入充值金额");
                    }else {
                        double num = Double.parseDouble(jine);
                        if(num >= 100){
                            ShowToast.showToast("你选择了支付宝支付");
                            boolean bbb = checkAliPayInstalled(ChongZhiActivity.this);
                            if(bbb){
                                AliPay(jine);
                            }else {
                                ShowToast.showToast("你尚未安装支付宝");
                            }

                        }else {
                            ShowToast.showToast("最低充值100元");
                        }
                    }

                }else if(temp == 0){
                    if(TextUtils.isEmpty(jine)){
                        ShowToast.showToast("请输入充值金额");
                    }else {
                        double num = Double.parseDouble(jine);
                        if(num >=100){
                            ShowToast.showToast("请选择一种支付方式");
                        }else {
                            ShowToast.showToast("最低充值100元");
                        }
                    }
                }
            }
        });

    }

    private void AliPay(String num) {
        MyRequest myRequest = new MyRequest(ConStans.ZhiFuUrl, RequestMethod.POST);
        myRequest.add("userid", Setting.getId());
        myRequest.add("total_amount",num);
        myRequest.add("type",3);
        CallServer.getInstance().addPost(this, myRequest, 3, new OnCallBack() {
            @Override
            public void OnSuccess(int what, String json, Object ject) {
                Log.e("支付宝参数",json);
                try {
                    JSONObject object = new JSONObject(json);
                    if(object.getInt("status") == 1){
                        String text = object.getString("data");
                        alipay(text);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void WeiXInPay(String num) {
        MyRequest myRequest = new MyRequest(ConStans.WeiXinZhiFuUrl, RequestMethod.POST);
        myRequest.add("userid",Setting.getId());
        myRequest.add("total_amount",num);
        myRequest.add("type",3);
        CallServer.getInstance().addGet(3, new OnCallBack() {
            @Override
            public void OnSuccess(int what, String json, Object ject) {
                Log.e("微信支付参数",json);
                try {
                    JSONObject object = new JSONObject(json);
                    if(object.getInt("status") == 1){
                        JSONObject object1 = object.getJSONObject("data");
                        req.appId = object1.getString("appid");
                        req.partnerId = object1.getString("partnerid");
                        req.prepayId = object1.getString("prepayid");
                        req.packageValue = object1.getString("package");
                        req.nonceStr = object1.getString("noncestr");
                        req.timeStamp = object1.getString("timestamp");
                        req.sign = object1.getString("sign");
                        sendPayReq();

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }, myRequest);
    }

    private PayReq req = new PayReq();
    private final IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
    private final String APP_ID = "wx7dec8b795b8c7bc3";

    /**
     * 调起微信支付
     */
    private void sendPayReq() {
        msgApi.registerApp(APP_ID);
        msgApi.sendReq(req);
        Log.e(">>>>>", req.partnerId);
    }

    //去支付宝支付
    public void alipay(final String data) {

        // 完整的符合支付宝参数规范的订单信息
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(ChongZhiActivity.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(data);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_CHECK_FLAG = 2;


    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {

                    PayResult payResult = new PayResult((String) msg.obj);
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {

                        Toast.makeText(ChongZhiActivity.this, "支付成功", Toast.LENGTH_SHORT).show();

                    } else {
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(ChongZhiActivity.this, "支付结果确认中", Toast.LENGTH_SHORT).show();

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(ChongZhiActivity.this, "支付失败", Toast.LENGTH_SHORT).show();

                        }
                    }
                    break;
                }
                case SDK_CHECK_FLAG: {
                    Toast.makeText(ChongZhiActivity.this, "检查结果为：" + msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                }
            }
        }
    };

}
